import { create } from 'zustand';
import { persist } from 'zustand/middleware';
// 会话类型定义
export interface ChatSession {
  id: string;
  title: string;
  lastMessage: string;
  timestamp: Date;
  messageCount: number;
  agentName?: string;
}

// 聊天消息类型
interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: Date;
  status?: 'sending' | 'sent' | 'delivered' | 'error';
  reactions?: string[];
  isStreaming?: boolean;
}

// 定义聊天状态类型
interface ChatState {
  // UI 状态
  inputText: string;
  isLoading: boolean;

  // 选中状态
  selectedAgentId: string | null;

  // 数据状态
  chatMessages: ChatMessage[];
  chatSessions: ChatSession[];
  currentSessionId: string | undefined;

  // UI 状态 setters
  setInputText: (text: string) => void;
  setLoading: (loading: boolean) => void;
  setSelectedAgentId: (agentId: string | null) => void;

  // 聊天消息 setters
  setChatMessages: (messages: ChatMessage[]) => void;
  addChatMessage: (message: ChatMessage) => void;
  updateChatMessage: (id: string, updates: Partial<ChatMessage>) => void;
  clearChatMessages: () => void;

  // 会话 setters
  setChatSessions: (sessions: ChatSession[]) => void;
  setCurrentSessionId: (id: string | undefined) => void;
  addChatSession: (session: ChatSession) => void;
  removeChatSession: (id: string) => void;
  updateChatSession: (id: string, updates: Partial<ChatSession>) => void;

  // 新增方法
  createNewSession: () => string;
  loadChatSessions: () => Promise<void>;
  loadChatMessages: (sessionId: string) => Promise<void>;

  // 清除所有聊天相关状态
  resetChatState: () => void;
}

// 创建聊天 store
export const useChatStore = create<ChatState>()(
  persist(
    (set) => ({
      // 初始状态
      inputText: '',
      isLoading: false,
      selectedAgentId: null,
      chatMessages: [],
      chatSessions: [],
      currentSessionId: undefined,

      // UI 状态 setters
      setInputText: (text) => set({ inputText: text }),
      setLoading: (loading) => set({ isLoading: loading }),
      setSelectedAgentId: (agentId) => set({ selectedAgentId: agentId }),

      // 聊天消息 setters
      setChatMessages: (messages) => set({ chatMessages: messages }),
      addChatMessage: (message) => set((state) => ({
        chatMessages: [...state.chatMessages, message]
      })),
      updateChatMessage: (id, updates) => set((state) => ({
        chatMessages: state.chatMessages.map(msg =>
          msg.id === id ? { ...msg, ...updates } : msg
        )
      })),
      clearChatMessages: () => set({ chatMessages: [] }),

      // 会话 setters
      setChatSessions: (sessions) => set({ chatSessions: sessions }),
      setCurrentSessionId: (id) => set({ currentSessionId: id }),
      addChatSession: (session) => set((state) => ({
        chatSessions: [session, ...state.chatSessions]
      })),
      removeChatSession: (id) => set((state) => ({
        chatSessions: state.chatSessions.filter(session => session.id !== id),
        // 如果删除的是当前会话，清除当前会话 ID
        currentSessionId: state.currentSessionId === id ? undefined : state.currentSessionId
      })),
      updateChatSession: (id, updates) => set((state) => ({
        chatSessions: state.chatSessions.map(session =>
          session.id === id ? { ...session, ...updates } : session
        )
      })),

      // 新增方法
      createNewSession: () => {
        const newSession: ChatSession = {
          id: Date.now().toString(),
          title: "新会话",
          lastMessage: "",
          timestamp: new Date(),
          messageCount: 0,
        };
        set((state) => ({
          chatSessions: [newSession, ...state.chatSessions],
          currentSessionId: newSession.id,
          chatMessages: []
        }));
        return newSession.id;
      },

      loadChatSessions: async () => {
        // TODO: Implement API call to load sessions
        return Promise.resolve();
      },

      loadChatMessages: async (sessionId: string) => {
        // TODO: Implement API call to load messages for session
        return Promise.resolve();
      },

      // 清除所有聊天相关状态
      resetChatState: () => set({
        inputText: '',
        isLoading: false,
        selectedAgentId: null,
        chatMessages: [],
        chatSessions: [],
        currentSessionId: undefined
      }),
    }),
    {
      name: 'chat-storage',
      partialize: (state) => ({
        chatSessions: state.chatSessions,
        currentSessionId: state.currentSessionId
      }),
    }
  )
);
